export function setCache(key, data) {
  if (window.Cache == null) {
    window.Cache = {}
  }
  window.Cache[key] = data
}
export function getCache(key) {
  if (window.Cache == null) {
    return null
  }
  return window.Cache[key]
}

export function remove(key) {
  if (window.Cache !== null) {
    window.Cache[key] = null
  }
}
export function agentRequest<T>(key: string, reqFunc: Function): Promise<T> {
  const data = getCache(key)
  if (data != null) {
    return new Promise((resolve) => {
      resolve(JSON.parse(data))
    })
  } else {
    return new Promise(async (resolve, reject) => {
      try {
        await navigator.locks.request(key, async () => {
          const data = getCache(key)
          if (data != null) {
            resolve(JSON.parse(data))
          } else {
            const res = await reqFunc()
            setCache(key, JSON.stringify(res))
            resolve(res)
          }
        })
      } catch (e) {
        reject(e)
      }
    })
  }
}
